package com.xw.unification.interfaces;

import lombok.Getter;
import org.springframework.http.HttpStatus;

/**
 * 响应 Code 可枚举接口, 定义枚举必须实现该接口, 并在配置文件中配置
 *
 * @author qiwei
 * @date 2023-8-10 16:00:00
 * @since v1.0.0
 */
public interface ResultCodeEnumerable {

    Default DEFAULT = new Default();

    /**
     * 获取响应码
     * @return resultCode
     */
    int getCode();

    /**
     * 获取响应消息
     * @return resultMessage
     */
    String getMessage();

    @Getter
    class Default {

        private static boolean INIT_FLAG = false;
        private int successCode = HttpStatus.OK.value();
        private int errorCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
        private String successMsg = HttpStatus.OK.getReasonPhrase();
        private String errorMsg = HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();

        public synchronized void setDefaultSuccessAndErrorEnum(ResultCodeEnumerable successEnum, ResultCodeEnumerable errorEnum) {
            if (INIT_FLAG) {
                throw new IllegalStateException(
                        String.format("Default result code has been initialized, success: %d - %s, error: %d - %s",
                                this.successCode, this.successMsg, this.errorCode, this.errorMsg
                        ));
            }
            INIT_FLAG = true;
            if (!(successEnum instanceof Enum)) {
                throw new IllegalArgumentException("Default success code must be enum instance");
            }
            if (!(errorEnum instanceof Enum)) {
                throw new IllegalArgumentException("Default error code must be enum instance");
            }
            if (successEnum.getClass() != errorEnum.getClass()) {
                throw new IllegalArgumentException("Default success code and error code must be instance of same enum class");
            }
            if (successEnum.getCode() == errorEnum.getCode()) {
                throw new IllegalArgumentException("Default success code can not be equal to default error code");
            }
            this.successCode = successEnum.getCode();
            this.successMsg = successEnum.getMessage();
            this.errorCode = errorEnum.getCode();
            this.errorMsg = errorEnum.getMessage();
        }

    }
}
